package com.lujianfei.powersearch.ui.createOrUpdate.widget.imageviewedit

import android.content.Context
import android.net.Uri
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.lujianfei.powersearch.R
import com.lujianfei.powersearch.base.MovableAdapter
import com.lujianfei.powersearch.databinding.ImageviewEditItemBinding
import com.lujianfei.powersearch.databinding.WidgetImageviewEditlistBinding
import com.lujianfei.powersearch.ui.createOrUpdate.widget.imageviewedit.adapter.ImageViewEditAdapter
import com.lujianfei.powersearch.ui.createOrUpdate.widget.imageviewedit.model.ImageViewEditItem

class ImageViewEditList @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {

    private var binding: WidgetImageviewEditlistBinding ?= null
    val list = arrayListOf<ImageViewEditItem>()

    init {
        binding = WidgetImageviewEditlistBinding.inflate(LayoutInflater.from(context))
    }

    fun setImages(images:String?) {
        list.clear()
        if (images.isNullOrBlank()) return

        val imageArr = images.split(",")
        if (imageArr.isEmpty()) {
            list.add(ImageViewEditItem(imageUri = Uri.parse(images), type = ImageViewEditItem.TYPE_NORMAL))
        } else {
            imageArr.forEach {
                list.add(ImageViewEditItem(imageUri = Uri.parse(it), type = ImageViewEditItem.TYPE_NORMAL))
            }
        }
        list.add(ImageViewEditItem(imageUri = null, type = ImageViewEditItem.TYPE_ADD))

        val adapter = ImageViewEditAdapter()
        adapter.setData(list)
        val mLinearLayoutManager = LinearLayoutManager(context)
        mLinearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        binding?.imageEditList?.layoutManager = mLinearLayoutManager
        binding?.imageEditList?.adapter = adapter
    }
}

@BindingAdapter(value=["bindImageViewEditList"], requireAll = false)
fun bindImageViewEditList(widget:ImageViewEditList, images:String?) {
    widget.setImages(images)
}